<?php

namespace App\Console\Commands;

use App\AdminRecord;
use App\Customer;
use App\Lead;
use Illuminate\Console\Command;
use function foo\func;

class AdminRecordCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'admin:record';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '跟进记录绑上project_id';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $admin = AdminRecord::whereNull('project_id');
        $out = $this->output->createProgressBar($admin->count());
        $admin->chunkById(100, function ($adminRecords)use ($out) {
            foreach ($adminRecords as $record) {
                $out->advance();
                /**
                 * @var AdminRecord $record
                 */
                if ($record->types == 'crm_customer') {
                    $customer = Customer::whereCustomerId($record->types_id)->first();
                    if ($customer) {
                        $record->project_id = $customer->project_id;
                        $record->save();
                    }
                } elseif ($record->types == 'crm_leads') {
                    $leads = Lead::whereLeadsId($record->types_id)->first();
                    if ($leads) {
                        $record->project_id = $leads->project_id;
                        $record->save();
                    }
                }

            }
        });
        $out->finish();
    }
}
